package com.lw.leetcode.other.b;

import java.util.Arrays;

/**
 * @Author liw
 * @Date 2021/4/20 9:22
 * @Version 1.0
 */
public class Insert {

    public static void main(String[] args) {
//        int[][] a = {{1,2},{3,5},{6,7},{8,10},{12,16}};
        int[][] a = {{1,5}};
        int[] b = {2, 7};
        int[][] insert = new Insert().insert(a, b);
    }

    public int[][] insert(int[][] intervals, int[] newInterval) {
        int length = intervals.length;
        int a2 = newInterval[0];
        int b2 = newInterval[1];
        if (length == 0) {
            int[][] item = new int[1][2];
            item[0][0] = a2;
            item[0][1] = b2;
            return item;
        }
        int flag = 0;
        int[][] item = new int[length + 1][2];
        int a1;
        int b1;
        int index = 0;
        int i = 0;
        while (i < length) {
            a1 = intervals[i][0];
            b1 = intervals[i][1];
            if (a1 > b2) {
                item[index][0] = a2;
                item[index][1] = b2;
                flag = 2;
                break;
            } else if (a2 > b1) {
                item[index][0] = a1;
                item[index][1] = b1;
                index++;
                i++;
            } else {
                item[index][0] = Math.min(a1, a2);
                item[index][1] = Math.max(b1, b2);
                flag = 1;
                i++;
                break;
            }
        }

        if (flag == 0) {

            item[index][0] = a2;
            item[index][1] = b2;


        }
        if (flag == 1) {
            while (i < length) {
                int a = intervals[i][0];
                int b = intervals[i][1];
                if (a > item[index][1]) {
                    index++;
                    item[index][0] = a;
                    item[index][1] = b;
                } else {
                    item[index][1] = Math.max(b, item[index][1]);
                }
                i++;
            }
        }
        if (flag == 2) {
            while (i < length) {
                index++;
                item[index][0] = intervals[i][0];
                item[index][1] = intervals[i][1];
                i++;
            }
        }
        return Arrays.copyOf(item, index + 1);
    }




}
